package com.wstuo.common.tools.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.log4j.Logger;

import com.wstuo.common.tools.dto.FileInfoDTO;
import com.wstuo.common.tools.util.ToolsUtils;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.util.TimeUtils;

public class UploadFile implements IUploadFile {

	final static Logger LOGGER = Logger.getLogger(UploadFile.class);
    private static final String ATTACHMENT_PATH = AppConfigUtils.getInstance().getAttachmentPath();
    private LanguageContent lc = LanguageContent.getInstance();
    private static final String FILE_SEPARATOR = "/";
    private static final String FILE_PREVIEW_FLAG = "_pre.";
	/**
	 * 文件上传
	 */
	public FileInfoDTO uploadFile(FileInfoDTO fileInfo,String filedataFileName,File filedata,String fileExt,String flag) {
		fileInfo = new FileInfoDTO();	
		String fileType=filedataFileName.substring(filedataFileName.lastIndexOf(".")+1);
		if(fileExt.indexOf(fileType.toLowerCase())==-1){
		   fileInfo.setErr(lc.getContent("lable.Does.not.allow.file.uploads"));
		}
		if(filedata.length()==0){
			fileInfo.setErr(lc.getContent("lable.Contents.file.isempty"));
		}else{
			try{
	        	String fileFolder = TimeUtils.format(new Date(), "yyyyMMdd");
	    		String newFolder=ATTACHMENT_PATH+ FILE_SEPARATOR +fileFolder;
	    		if(flag!=null && flag.equals("editor")){
	    			newFolder=AppConfigUtils.getInstance().getEditorPath()+ FILE_SEPARATOR +fileFolder;
	    			fileFolder="../upload/editor/"+fileFolder;
		        }
	    		//如果目录不存在则创建
	    	    if (!(new File(newFolder).isDirectory())) {
	    	       new File(newFolder).mkdir();
	    	    }
	    	    long name = new Date().getTime();
	    	    String fileName = name + "." + fileType;
	    	    File imageFile = new File(newFolder+ FILE_SEPARATOR +fileName);
	        	fileInfo.setFileSize(filedata.length());
	        	
	    		ToolsUtils.copy(filedata, imageFile);
	    		
		        fileInfo.setErr("");
		        fileInfo.setMsg(fileFolder+ FILE_SEPARATOR +fileName);
				fileInfo.setPre( fileInfo.getMsg() );

				//判断附件是否为图片
		        if ( ATTACHMENT_TYPE_IMAGE.indexOf( fileType.toLowerCase() ) > -1 ) {//100KB
			        String previewName = name + FILE_PREVIEW_FLAG + fileType;
		        	if (fileInfo.getFileSize() > 102400 ) {
		        		fileInfo.setPre(fileFolder+ FILE_SEPARATOR + previewName);
			        	createAttaImagePreview(imageFile,newFolder, previewName , fileType);
					}
		        }
	        } catch ( Exception ex ){
	        	LOGGER.error(ex);
	        	//抛出异常
	        	throw new ApplicationException("ERROR_FILEUPLOAD \n"+ex,ex);
	        }
		}
		return fileInfo;
	}
	
	/**
	 * 文件删除
	 */
	public void deleteFile(String deleteFileName) {
	    try{
			String fileFolder = TimeUtils.format(new Date(), "yyyyMMdd");
	    	File file=new File(ATTACHMENT_PATH+"/"+fileFolder+"/"+deleteFileName);
	    	if(file.exists()){
	    		file.delete();
	    	}
	    }
    	catch(Exception ex){
    		//抛出异常
        	throw new ApplicationException("ERROR_ON_DELETEATTACHMENT \n"+ex,ex);
    	}

	}

	/**
	 * @param srcAtta
	 * @param path
	 * @param newFileName
	 * @param fileType
	 */
	public void createAttaImagePreview(final File srcAtta,final String path, final String newFileName,final String fileType) {
		try {
			BufferedImage imageBuf = ImageIO.read( srcAtta );
			BufferedImage thumbnail = Thumbnails.of(imageBuf)
			        .scale( getScale( srcAtta.length() ) )
			        .asBufferedImage();
			ImageIO.write(thumbnail, fileType, new File(path + FILE_SEPARATOR + newFileName));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取图片的压缩率
	 * @param fileSize
	 * @return
	 */
	public double getScale(long fileSize) {
		double scale = 0.25f;
		long size = fileSize ;
		if (size >= 104857600){//100MB
			scale = 0.1f;
		}else if (size >= 20971520) {//20MB
			scale = 0.2f;
		}else if (size >= 10485760) {//10MB
			scale = 0.3f;
		}else if (size >=  5242880) {//5MB
			scale = 0.4f;
		}else if (size >=  3145728) {//3MB
			scale = 0.6f;
		}else if (size >=  1048576) {//1MB
			scale = 0.8f;
		}else {
			scale = 0.9f;
		}
		return scale;
	}
}
